package com.sjft.cloud.commons.security.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Retryer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

import static java.util.concurrent.TimeUnit.SECONDS;


/**
 * FeignInterceptor
 *
 * @author Jin
 */
@Slf4j
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            if (authentication instanceof OAuth2Authentication) {
                OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
                String access_token = details.getTokenValue();
                requestTemplate.header("Authorization", OAuth2AccessToken.BEARER_TYPE + " " + access_token);
            }
        }
    }


    @Bean
    public Retryer feignRetry() {
        return new Retryer.Default(200, SECONDS.toMillis(2), 10);
    }
}
